<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\MemberModel;
class Wxsdk extends Controller
{
    public function getUserOpenId(){
        $appid='wx77bbae81f989556c';
        $appsecret='f7c7a404c7f5ef43ae7ba7816bbb91c6';
		$code = $_GET['code'];

        //2.获取到网页授权的access_token 
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        //3.拉取用户的openid
        $res = $this->https_request($url);
		$result = $this->getUserinfo($res['openid']);
		$indexUrl = url('index/index');
		$this->redirect($indexUrl);
    }
	
	public function getUserinfo($openid)
	{
		//全局获取access_token
		if(empty(session('access_token'))){
			$this->get_access_token();
		}
		$access_token = session('access_token');

		$url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		//用户基本信息
		$userinfo = $this->https_request($url);
		
		$userinfo['addtime'] = time();
		$userinfo['pid'] = substr($userinfo['qr_scene_str'],1);
		$userinfo['qr_scene_str'] = substr($userinfo['qr_scene_str'],0,1);
		//保存会员数据
		return $tag = $this->saveUserInfo($userinfo);
	}
	
	public function saveUserInfo($userinfo)
	{
		$member = new MemberModel();
        $result = $member->getOneMember($userinfo['openid']);
        if($result){
			session('uname',$result['nickname']);
            session('uid',$result['id']);
			session('expire',7200);
			$tag = 1;
        }else{
            $flag = $member->save($userinfo);
            if($flag){
				session('uname', $userinfo['nickname']);
				session('uid', $flag);
				session('expire',7200);
            }
			$tag = 0;
        }
		return $tag;
	}
	
	//推广二维码 永久
	public function getTgQrCode()
	{
		//全局获取access_token
		if (empty('access_token')) {
			$this->get_access_token();
		}
		$access_token = session('access_token');
		//获取 ticket 票据
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
		$scene_str = '1'.session('id');

		$postArr = array(
			'action_name'=> "QR_LIMIT_STR_SCENE",
			'action_info'=>array(
				'scene'=> array('scene_str'=>$scene_str),
			)
		);
		$postJson = json_encode($postArr);
		$res = $this->https_request($url,'post','json',$postJson);
		$ticket = $res['ticket'];
		//使用 ticket获取二维码
		$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
		$imaginfo = $this->downloadWeixinFile($url);
		$time = time();           
		$filename = $time.session('uid').'.jpg';
		$newfolder="upload/tgqrcode/";//文件夹名称 
		$local_file = fopen($newfolder.$filename,"a");
		if (false !== $local_file){ 
			if (false !== fwrite($local_file, $imaginfo["body"])) {  
				fclose($local_file);
				$member = new MemberModel();
				if($member->where('id',session('uid'))->update(['tg_qrcode'=>"/".$newfolder.$filename])){
					return $filepath = '/'.$newfolder.$filename;
				}
				// return $res = $member->where('id',session('uid'))->update(['tg_qrcode'=>"/".$newfolder.$filename]);
			}
		}
	}

	//邀请二维码 永久
	public function getYqQrCode()
	{
		//全局获取access_token
		if (empty('access_token')) {
			$this->get_access_token();
		}
		$access_token = session('access_token');
		//获取 ticket 票据
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
		$scene_str = '2'.session('uid');

		$postArr = array(
			'action_name'=> "QR_LIMIT_STR_SCENE",
			'action_info'=>array(
				'scene'=> array('scene_str'=>$scene_str),
			)
		);
		$postJson = json_encode($postArr);
		$res = $this->https_request($url,'post','json',$postJson);
		$ticket = $res['ticket'];
		//使用 ticket获取二维码
		$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
		$imaginfo = $this->downloadWeixinFile($url);
		$time = time();           
		$filename = $time.session('uid').'.jpg';
		$newfolder="upload/yqqrcode/";//文件夹名称 
		$local_file = fopen($newfolder.$filename,"a");
		if (false !== $local_file){ 
			if (false !== fwrite($local_file, $imaginfo["body"])) {  
				fclose($local_file);
				$member = new MemberModel();
				if($member->where('id',session('uid'))->update(['yq_qrcode'=>"/".$newfolder.$filename,'qr_scene_str'=>'10'])){
					return $filepath = '/'.$newfolder.$filename;
				}
				// return $res = $member->where('id',session('uid'))->update(['yq_qrcode'=>"/".$newfolder.$filename]);
			}
		}
	}
	
	//下载二维码
	public function downloadWeixinFile($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_NOBODY,0);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$package = curl_exec($ch);
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		return array_merge(array('body'=>$package),array('header'=>$httpinfo));
	}
	
    public function https_request($url,$type='get',$res='json',$data = ''){
        //1.初始化curl
        $curl = curl_init();
        //2.设置curl的参数
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,2);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if ($type == "post"){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        //3.采集
        $output = curl_exec($curl);
        //4.关闭
        curl_close($curl);
        if ($res == 'json') {
            return json_decode($output,true);
        }
    }
	
	/*public function get_access_token() 
	{
		$tokenFile = "./accesstoken.txt";//缓存文件名
		$data = json_decode(file_get_contents($tokenFile));
		
		if ($data->expire_time < time() or !$data->expire_time){
			//开发者的appid和appsecret
			$appid='wx77bbae81f989556c';
	        $appsecret='f7c7a404c7f5ef43ae7ba7816bbb91c6';
			//access_token获取地址：
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
			//1.实例化（初始化curl）  
			$curl = curl_init();
			//2.设置curl参数
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在  
			//3. 数据采集
			$res= curl_exec($curl);
			//4. 关闭
			curl_close($curl);
			$arr = json_decode($res,true);
			$access_token = $arr['access_token'];
			  if($access_token) {
			  	$data->expire_time = time()+7000;
			  	$data->access_token = $access_token;
				$fp = fopen($tokenFile, "w");
				fwrite($fp, json_encode($data));
				fclose($fp);
			  }
		}else{
		  $access_token = $data->access_token;
		}
		return $access_token;
	}*/
	
	public function get_access_token(){
		//开发者的appid和appsecret
		$appid='wx77bbae81f989556c';
        $appsecret='f7c7a404c7f5ef43ae7ba7816bbb91c6';
		//access_token获取地址：
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;

		//1.实例化（初始化curl）  
		$curl = curl_init();
		//2.设置curl参数
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在  
		//3. 数据采集
		$res= curl_exec($curl);
		//4. 关闭
		curl_close($curl);
		$arr = json_decode($res,true);
		
		//得到的access_token
		//当前token获取时间
		$access_token_time = time();
		//access_token和token_time存到session中
		session('access_token',$arr['access_token']);
		session('access_token_time',$access_token_time);
    }
}